<script lang="ts" setup></script>

<script lang="ts">
import routes from '@/router/routes'
import { h } from 'vue'
import { AppstoreOutlined } from '@ant-design/icons-vue'
import { translateRouteTitle } from '@/libs/utils/RouteTitle'

export default {
	name: 'Layouts_basic_Menus',

	data() {
		return {
			permissions: [],
			selectedKeys: [],
			openKeys: [],
			menus: []
		}
	},
	mounted() {
		this.permissions = useAdminerStore().getPermissions
		this.updateMenus()
		this.setMenusIcon()
		this.openKeys = this.getOpenKeys()
		this.selectedKeys = this.getSelectedKeys()
	},
	watch: {
		'$i18n.locale'() {
			this.updateMenus()
		}
	},
	methods: {
		/**
		 * 更新菜单数据
		 */
		updateMenus() {
			const menus = this.route2menus(routes)
			this.menus = this.getMenusTree(menus)
		},
		/**
		 * 从路由表中获取需要展示的菜单
		 * @param routes
		 */
		route2menus(routes: any): any[] {
			let menus = []
			routes.forEach(item => {
				if (item.path === '/') menus = item.children
			})
			return menus
		},
		/**
		 * 获取菜单树
		 * @param routes
		 */
		getMenusTree(routes: any): any[] {
			const menusTree: any[] = []
			for (const item of routes) {
				if (
					useAdminerStore().getAdminer.is_super === Enums.common.isDatas.Y[0] ||
					!item.meta.permission ||
					this.$_.includes(this.permissions, item.meta.permission)
				) {
					if (item.meta.isMenu) {
						const menu = {
							key: item.path,
							path: item.path,
							label: translateRouteTitle(item.meta.title),
							permission: item.meta.permission || '',
							children: false
						}
						if (import.meta.env.VITE_ENV !== 'local') {
							if (menu.key === '/test') {
								continue
							}
						}
						if (item.showSubMenu && item.children) {
							menu.children = this.getMenusTree(item.children)
						}
						menusTree.push(menu)
					}
				}
			}
			return menusTree
		},
		/**
		 * 设置根菜单图标
		 */
		setMenusIcon() {
			this.menus.forEach((item: any) => {
				item.icon = () => h(AppstoreOutlined)
			})
		},
		getOpenKeys() {
			const keys: any = []
			this.$route.matched.forEach((item: any) => {
				if (item.meta.isMenu) {
					keys.push(item.path)
				}
			})
			return keys
		},
		getSelectedKeys() {
			const route = this.$route
			const selectedKey = route.isMenu ? route.path : this.$_.last(this.openKeys)
			return [selectedKey]
		},
		toMenuRoute(e: any) {
			// Api.authTo(e.item.permission, e.item.path)
			this.$router.push(e.item.path)
		}
	}
}
</script>

<template>
	<view>
		<a-menu
			theme="dark"
			v-model:openKeys="openKeys"
			v-model:selectedKeys="selectedKeys"
			style="width: 200px; overflow-y: auto"
			mode="inline"
			:items="menus"
			@click="toMenuRoute"></a-menu>
	</view>
</template>

<style scoped lang="scss"></style>
